/**
 * API请求工具函数
 */

// 日志函数
function log(type: 'info' | 'error', message: string, data?: any) {
  const timestamp = new Date().toISOString()
  console.log(`[${timestamp}] [${type}] ${message}`)
  if (data) {
    console.log('Details:', data)
  }
}

interface ApiResponse {
  status: string
  text?: string
  error?: string
}

interface AudioData {
  buffer: ArrayBuffer
  type: string
}

/**
 * 通过background script发送音频数据到后端处理
 * @param audioData 音频数据
 * @returns Promise<ApiResponse>
 */
export async function sendToBackend(audioData: AudioData): Promise<ApiResponse> {
  const maxRetries = 3
  let lastError: Error | null = null

  log('info', '开始发送音频数据', {
    type: audioData.type,
    size: audioData.buffer.byteLength
  })

  for (let i = 0; i < maxRetries; i++) {
    try {
      log('info', `尝试第 ${i + 1} 次请求`)
      
      const result = await new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(
          { 
            type: 'SEND_TO_BACKEND',
            audioData
          },
          response => {
            if (chrome.runtime.lastError) {
              log('error', 'Chrome运行时错误', {
                message: chrome.runtime.lastError.message
              })
              reject(new Error(chrome.runtime.lastError.message))
              return
            }
            if (response?.success) {
              log('info', '请求成功', { response })
              resolve(response.data)
            } else {
              log('error', '请求失败', { response })
              reject(new Error(response?.error || 'API请求失败'))
            }
          }
        )
      })
      
    } catch (error) {
      lastError = error as Error
      log('error', `第 ${i + 1} 次请求失败`, {
        error: lastError.message,
        stack: lastError.stack
      })
      
      if (i === maxRetries - 1) {
        log('error', '所有重试都失败')
        throw error
      }
      
      const delay = 1000 * (i + 1)
      log('info', `等待 ${delay}ms 后重试`)
      await new Promise(resolve => setTimeout(resolve, delay))
    }
  }

  throw lastError || new Error('请求失败')
} 